package com.cscec.omega.service;


import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.s3.model.S3Object;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * 移动云对象存储
 */
@Service
public class OSSService {

    private static Logger logger = LoggerFactory.getLogger(OSSService.class);

    private final String ACCESSKEY = "GJ0ZX6A75G5V3GCK6FC5";
    private final String SECRETKEY = "M2rrfjF252IX8iAk0TSu18hdUnzZWQFdxwE2Dp0m";
    private final String HOSTNAME = "eos-wuxi-1.cmecloud.cn:443";
    private final String BUCKETNAME = "czgse";

    private AmazonS3Client client = new AmazonS3Client();
    public void init(){
        ClientConfiguration opts = new ClientConfiguration();
        opts.setSignerOverride("S3SignerType");
        AWSCredentials credentials = new BasicAWSCredentials(ACCESSKEY, SECRETKEY);
        client = new AmazonS3Client(credentials, opts);
        client.setEndpoint(HOSTNAME);

        //关闭client，之后不能再被使用
//        client.shutdown();
    }

    /**
     * 创建bucket
     */
    public void createBucket(String bucketName){
        //判断bucket是否存在
        boolean exists = client.doesBucketExist(bucketName);
        if (exists){
            logger.info("bucket： {}已存在", bucketName);
            return;
        }
        Bucket bucket = client.createBucket(bucketName);
        logger.info("bucket: {}", bucket);
    }

    /**
     * 列举bucket
     * @return
     */
    public List<Bucket> bucketList(){
        init();
        List<Bucket> list = client.listBuckets();
        client.shutdown();
        return list;
    }

    /**
     * 上传图片
     */
    public void upload(String objectKey, InputStream inputStream){
        init();
        PutObjectResult result = client.putObject(BUCKETNAME, objectKey, inputStream, null);
        logger.info("upload img result: {}", result);
        client.shutdown();
    }

    /**
     * 下载文件
     */
    public void download(String objectKey, HttpServletResponse response) throws IOException {
        init();
        S3Object s3Object = client.getObject(BUCKETNAME, objectKey);
//        InputStream fis = s3Object.getObjectContent();
//        byte[] buffer = new byte[1024];
//        fis.read(buffer);
//        fis.close();


        // 清空response
        response.reset();
        // 设置response的Header
        response.setCharacterEncoding("UTF-8");
        //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
        //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
        // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(objectKey+".jpg", "UTF-8"));

        ServletOutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
        while ((len = s3Object.getObjectContent().read(b)) > 0) {
            outputStream.write(b, 0, len);
        }
        s3Object.getObjectContent().close();
        client.shutdown();

        // 告知浏览器文件的大小
//        response.addHeader("Content-Length", "" + buffer.length);
//        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
//        response.setContentType("application/octet-stream");
//        outputStream.write(buffer);
//        outputStream.flush();
    }

    /**
     * 删除对象
     * @param objectKey
     */
    public void delete(String objectKey){
        init();
        client.deleteObject(BUCKETNAME, objectKey);
        client.shutdown();
    }
}
